//
//  ViewController.swift
//  CocoaPodsDemo
//
//  Created by satoshi_umaM1 on 2022/2/8.
//   https://github.com/a1049145827/BSText

import BSText
import Lantern
import Photos
import UIKit
import ZLPhotoBrowser

class ViewController: UIViewController {
    var label: BSLabel!

    let config = ZLPhotoConfiguration.default()

    let languages: [ZLLanguageType] = [.system, .english, .chineseSimplified, .chineseTraditional, .japanese, .french, .german, .russian, .vietnamese, .korean, .malay, .italian]

    private var showCellMore: Bool = false
    @IBOutlet var tempImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        config.languageType = .chineseSimplified

        tempImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(onTap(sender:)))
        tap.numberOfTapsRequired = 1
        tap.numberOfTouchesRequired = 1
        tempImageView.addGestureRecognizer(tap)

        var ss = 2
        var s = 1
        交换参数(&ss, &s)
//        print(ss)
//        print(s)

//        形式参数 (Int, Int) -> Int 
        let 新函数类型: (Int, Int) -> Int = 函数类型_乘
        let 新函数类型加: (Int, Int) -> Int = 函数类型_加

        print(新函数类型(2, 2))
        print(新函数类型加(1, 2))
        
    }

    func 函数类型_加(num: Int, num2: Int) -> Int {
        return num + num2
    }

    func 函数类型_乘(num: Int, num2: Int) -> Int {
        return num * num2
    }

    func 交换参数(_ a: inout Int, _ b: inout Int) {
        let tempA = a
        a = b
        b = tempA
    }

    @IBAction func 展开收起(_ sender: Any) {
//        if showCellMore {
//            upLabel()
//        } else {
//            backLabel()
//        }
//        showCellMore = !showCellMore

//        YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:CGSizeMake(SCREEN_WIDTH - commentLeftMargin * 2, CGFLOAT_MAX) text:self.showingAttribute];
//                _commentHeight = layout.textBoundingSize.height;
//                NSLog(@"YY计算-%f",_commentHeight);

        //                let loginVC = MainNavVC(rootViewController: LoginVC())
        let loginVC = HumanViewController()
//        loginVC.modalPresentationStyle = .fullScreen
        present(loginVC, animated: true) { }
    }

    func backLabel() {
        let text1 = NSMutableAttributedString()
        let title = "戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作"
        text1.append(NSMutableAttributedString(string: title, attributes: nil))
        text1.bs_font = UIFont.systemFont(ofSize: 16)

        label = BSLabel()
        label.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 200)
        label.isUserInteractionEnabled = true
        label.numberOfLines = 3
        label.textVerticalAlignment = .top
        label.attributedText = text1

        addSeeMoreButton()

        let layout = TextLayout(containerSize: CGSize(width: view.frame.width, height: 200), text: text1)
        print("------\(layout?.textBoundingSize.height)")

        view.addSubview(label)
    }

    func upLabel() {
        let text1 = NSMutableAttributedString()
        let title = "戴海江，女，主任医师、教授，北京同仁医院主任医师耳科专家、北京首大眼耳鼻喉医院特聘专家。毕业于首都医科大学医疗系，从事临床工作"
        text1.append(NSMutableAttributedString(string: title, attributes: nil))
        text1.bs_font = UIFont.systemFont(ofSize: 16)

        label = BSLabel()
        label.frame = CGRect(x: 0, y: 100, width: view.frame.size.width, height: 200)
        label.isUserInteractionEnabled = true
        label.numberOfLines = 2
        label.textVerticalAlignment = .top
        label.attributedText = text1

        addSeeMoreButton()

        view.addSubview(label)
    }

    /// 末尾 展开更多 按钮
    func addSeeMoreButton() {
        weak var _self = self

        let text = NSMutableAttributedString(string: "...【展开更多】")
        let hi = TextHighlight()

        text.bs_set(color: UIColor.red, range: ((text.string as NSString?)?.range(of: "【展开更多】"))!)
        text.bs_set(textHighlight: hi, range: ((text.string as NSString?)?.range(of: "【展开更多】"))!)
        text.bs_font = label.font

        hi.color = UIColor.orange
        hi.tapAction = { containerView, text, range, rect in
            _self?.label.numberOfLines = 0
            _self?.label.sizeToFit()
            print("--- text ---\(containerView)---\(text)---\(rect)---\(range)---\(_self?.label.frame.height)")
        }

        let seeMore = BSLabel()
        seeMore.attributedText = text
        seeMore.sizeToFit()

        let truncationToken = NSAttributedString.bs_attachmentString(with: seeMore, contentMode: UIView.ContentMode.center, attachmentSize: seeMore.size, alignTo: text.bs_font, alignment: TextVerticalAlignment.center)
        label.truncationToken = truncationToken
    }

    @objc func onTap(sender: UITapGestureRecognizer) {
        print("\n-------UITapGestureRecognizer--------\n")

        let lantern = Lantern()
        lantern.numberOfItems = {
            3
        }

        lantern.reloadCellAtIndex = { context in
            let lanternCell = context.cell as? LanternImageCell
            lanternCell?.imageView.image = self.tempImageView.image
        }

        // UIPageIndicator样式的页码指示器
        lantern.pageIndicator = LanternDefaultPageIndicator()
        lantern.pageIndex = 1
        lantern.show()
    }

    @IBAction func 快速选择(_ sender: UIButton) {
        let ps = ZLPhotoPreviewSheet()
        ps.selectImageBlock = { [weak self] images, assets, isOriginal in
            // your code
            print("\n----\(#function) in \(type(of: self))----\n\(images[0])\n\(assets)\n\(isOriginal)\n")
            self?.tempImageView.image = images[0]
        }
        ps.showPreview(animate: true, sender: self)
    }

    @IBAction func 进入相册选择(_ sender: UIButton) {
//        let ps = ZLPhotoPreviewSheet()
//        ps.selectImageBlock = { [weak self] (images, assets, isOriginal) in
//            print("\n----\(#function) in \(type(of: self))----\n\(images[0])\n\(assets)\n\(isOriginal)\n")
//            self?.tempImageView.image = images[0]
//        }
//        ps.showPhotoLibrary(sender: self)
        let camera = ZLCustomCamera()
        camera.takeDoneBlock = { [weak self] image, videoUrl in
            self?.save(image: image, videoUrl: videoUrl)
        }
        showDetailViewController(camera, sender: nil)
    }

    func save(image: UIImage?, videoUrl: URL?) {
        let hud = ZLProgressHUD(style: ZLPhotoConfiguration.default().hudStyle)
        if let image = image {
            hud.show()
            ZLPhotoManager.saveImageToAlbum(image: image) { [weak self] suc, asset in
                if suc, let at = asset {
//                    self?.selectedImages = [image]
//                    self?.selectedAssets = [at]
//                    self?.collectionView.reloimport PhotosadData()
                } else {
                    debugPrint("保存图片到相册失败")
                }
                hud.hide()
            }
        } else if let videoUrl = videoUrl {
            hud.show()
            ZLPhotoManager.saveVideoToAlbum(url: videoUrl) { [weak self] suc, asset in
                if suc, let at = asset {
                    self?.fetchImage(for: at)
                } else {
                    debugPrint("保存视频到相册失败")
                }
                hud.hide()
            }
        }
    }

    func fetchImage(for asset: PHAsset) {
        let option = PHImageRequestOptions()
        option.resizeMode = .fast
        option.isNetworkAccessAllowed = true

        PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width: 100, height: 100), contentMode: .aspectFill, options: option) { _, info in
            var downloadFinished = false
            if let info = info {
                downloadFinished = !(info[PHImageCancelledKey] as? Bool ?? false) && (info[PHImageErrorKey] == nil)
            }
            let isDegraded = (info?[PHImageResultIsDegradedKey] as? Bool ?? false)
            if downloadFinished, !isDegraded {
//                self.selectedImages = [image!]
//                self.selectedAssets = [asset]
//                self.collectionView.reloadData()
            }
        }
    }
}

extension UIView {
    /**
     Shortcut to set the view.layer's shadow

     @param color  Shadow Color
     @param offset Shadow offset
     @param radius Shadow radius
     */
    @objc func setLayerShadow(_ color: UIColor?, offset: CGSize, radius: CGFloat) {
        if let aColor = color?.cgColor {
            layer.shadowColor = aColor
        }
        layer.shadowOffset = offset
        layer.shadowRadius = radius
        layer.shadowOpacity = 1
        layer.shouldRasterize = true
        layer.rasterizationScale = UIScreen.main.scale
    }

    /**
     Remove all subviews.

     @warning Never call this method inside your view's drawRect: method.
     */
    @objc func removeAllSubviews() {
        // [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
        while subviews.count > 0 {
            subviews.last?.removeFromSuperview()
        }
    }

    /**
     Returns the view's view controller (may be nil).
     */
    @objc var viewController: UIViewController? {
        var view: UIView? = self
        while view != nil {
            let nextResponder = view?.next
            if nextResponder is UIViewController {
                return nextResponder as? UIViewController
            }
            view = view?.superview
        }
        return nil
    }

    /// < Shortcut for frame.origin.x.
    @objc var left: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.origin.x = newValue
            self.frame = frame
        }
        get {
            return frame.origin.x
        }
    }

    /// < Shortcut for frame.origin.y
    @objc var top: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.origin.y = newValue
            self.frame = frame
        }
        get {
            return frame.origin.y
        }
    }

    /// < Shortcut for frame.origin.x + frame.size.width
    @objc var right: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.origin.x = newValue - frame.size.width
            self.frame = frame
        }
        get {
            return frame.origin.x + frame.size.width
        }
    }

    /// < Shortcut for frame.origin.y + frame.size.height
    @objc var bottom: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.origin.y = newValue - frame.size.height
            self.frame = frame
        }
        get {
            return frame.origin.y + frame.size.height
        }
    }

    /// < Shortcut for frame.size.width.
    @objc var width: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.size.width = newValue
            self.frame = frame
        }
        get {
            return frame.size.width
        }
    }

    /// < Shortcut for frame.size.height.
    @objc var height: CGFloat {
        set {
            var frame: CGRect = self.frame
            frame.size.height = newValue
            self.frame = frame
        }
        get {
            return frame.size.height
        }
    }

    /// < Shortcut for center.x
    @objc var centerX: CGFloat {
        set {
            center = CGPoint(x: newValue, y: center.y)
        }
        get {
            return center.x
        }
    }

    /// < Shortcut for center.y
    @objc var centerY: CGFloat {
        set {
            center = CGPoint(x: center.x, y: newValue)
        }
        get {
            return center.y
        }
    }

    /// < Shortcut for frame.origin.
    @objc var origin: CGPoint {
        set {
            var frame: CGRect = self.frame
            frame.origin = newValue
            self.frame = frame
        }
        get {
            return frame.origin
        }
    }

    /// < Shortcut for frame.size.
    @objc var size: CGSize {
        set {
            var frame: CGRect = self.frame
            frame.size = newValue
            self.frame = frame
        }
        get {
            return frame.size
        }
    }
}

class Screen: NSObject {
    /// Screen Height With Portrait
    @objc static let height = max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    /// Screen Width With Portrait
    @objc static let width = min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
    /// Screen Size With Portrait
    @objc static let size = CGSize(width: width, height: height)
}
